import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const BannerSchema = new mongoose.Schema({
    title: String, // 备注
    img: String, // 图片
    url: String, // 跳转地址
    createTime: Number,
});

BannerSchema.methods.saveBanner = function (banner, cb) {
    banner.createTime = moment().unix();
    this.model('banner').insertMany([banner], cb);
};

BannerSchema.methods.getBanners = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const bannerModel = this.model('banner');
    bannerModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        bannerModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, banners) => cb(err, banners, count, hasMore));
    });
};

BannerSchema.methods.getAllBanners = function (query, cb) {
    this.model('banner').find(query, cb);
};

BannerSchema.methods.getBanner = function (query, cb) {
    this.model('banner').findOne(query, cb);
};

BannerSchema.methods.updateBanner = function (banner, cb) {
    const _id = banner._id;
    delete banner._id;
    this.model('banner').findOneAndUpdate({ _id }, { $set: banner }, cb);
};

BannerSchema.methods.removeBanners = function (bannerIds, cb) {
    this.model('banner').remove({ _id: { $in: bannerIds } }, cb);
};

export default db.model('banner', BannerSchema);